<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Api;

use App\Model\Upload;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Upload\UploadedFile;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

#[Controller]
class FileController
{
    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;

    #[Inject]
    protected RequestInterface $request;

    #[RequestMapping(path: "upload", methods: "post")]
    public function upload()
    {
        $file = $this->request->file('file');
        /** @var UploadedFile $file */
        if (!$file->isValid()) {
            return false;
        }

        $md5 = md5_file($file->getRealPath());
        $mimeType = $file->getMimeType();
        $size = $file->getSize();
        /** @var Upload $upload */
        $upload = Upload::getByMd5($md5);
        if ($upload) {
            return self::jsonResponse(200, 'success', $upload->toApi());
        }

        if (!file_exists(BASE_PATH . '/public/upload/' . date('Y-m-d'))) {
            mkdir(BASE_PATH . '/public/upload/' . date('Y-m-d'));
        }

        $name = time() . rand(1000, 9999) . '.' . $file->getExtension();
        $path = '/public/upload/' . date('Y-m-d') . '/' . $name;

        $file->moveTo(BASE_PATH . $path);

        if (!$file->isMoved()) {
            return self::jsonResponse(400, '上传失败,请联系管理员');
        }
        $data = [
            'path' => $path,
            'url' => env('FILE_URL', 'http://127.0.0.1:8080') . '/upload/' . date('Y-m-d') . '/' . $name,
            'size' => $size,
            'name' => $name,
            'mime_type' => $mimeType,
            'md5' => $md5,
        ];

        $upload = new Upload($data);
        $upload->save();

        return self::jsonResponse(200, 'success', $upload->toApi());
    }

    /**
     * 返回统一的json
     * @param int $status
     * @param $message
     * @param $data
     * @param $headerStatus
     * @return false|string
     */
    public static function jsonResponse(int $status = 1, $message = 'success', $data = null, $headerStatus = 200)
    {
        if (is_array($message)) {
            $data = $message;
            $message = 'success';
        }
        if (empty($data)) {
            $data = new class {
            };
        }

        return json_encode(['status' => $status, 'message' => $message, 'data' => $data]);

//        return response()->json(
//            ['status' => $status, 'message' => $message, 'data' => $data],
//            $headerStatus,
//            [],
//            JSON_UNESCAPED_UNICODE
//        );
    }
}
